<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>JS手动实现new</title>

    <script>

        
        function Person (name,age){
            this.name = name;
            this.age = age;
            this.say = function () {
                console.log("I am " + this.name)
            }
        }


        function myNew(className, ...params){

            let obj = {
                __proto__: className.prototype
            };

            obj.constructor(...params);
            return obj;

        }

        function myNew2 () {
            //创建一个新对象
            let obj  = {};
            //获得构造函数
            let Con = [].shift.call(arguments);
            //链接到原型（给obj这个新生对象的原型指向它的构造函数的原型）
            obj.__proto__ = Con.prototype;
            //绑定this
            let result = Con.apply(obj,arguments);
            //确保new出来的是一个对象
            return typeof result === "object" ? result : obj
        }

        function _new(fun) {
            return function() {
                let obj = {
                __proto__: fun.prototype
                }
                fun.apply(obj, arguments)
                return obj
            }
        }

        console.log(myNew(Person, "tom", 12));
        console.log(myNew(String, "xxx"));
        console.log('===============');

        console.log(myNew2(Person, "tom", 12));
        console.log(myNew2(String, "xxx"));

        //无论哪种写法，对于String都不好使
        console.log('===============');
        console.log(_new(String)('LL'));
        
        

    </script>
</head>

<body>

</body>

</html>